import React, { Component } from 'react';
import { connect } from 'umi'
import { PlusOutlined, ArrowRightOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import {
  Card,
  Button,
  Table,
  Space,
  Modal,
  message
} from 'antd';

import AddForm from './component/AddForm'
import UpdateForm from './component/UpdateForm'
import { reqAddCategory, reqUpdateCategory } from './service'

class index extends Component {

  state = {
    form: {},  // 子组件form方法
    parentId: '0',  // 当前需要显示的分类列表的parentId
    parentName: '', // 当前需要显示的分类名称
    categoryName: '', // 当前需要显示的分类名称
    showStaus: 0, // 添加/修改列表对话框的显示 0: 都不显示, 1: 显示添加, 2: 显示修改
    categorys: [], // 一级分类列表
    subCategorys: [], // 二级分类列表
    categoryId: '', // 分类id
    allFields: [
      {
        name: ['categoryName'],
        value: ''
      },
    ],
    addAllFields: [
      {
        name: ['parentId'],
        value: '0'
      },
      {
        name: ['categoryName'],
        value: ''
      },
    ]
  }

  columns = [
    {
      title: '分类的名称',
      dataIndex: 'name',
      key: 'name',
      // render: text => <a>{text}</a>,
    },
    {
      title: '操作',
      key: 'action',
      width: '30%',
      render: (category) => (
        <Space size="middle">
          <Button onClick={() => this.showUpdateModal(category)} type="link" >修改分类</Button>
          {
            this.state.parentId === '0' ? (
              <Button type="link" onClick={() => this.showSubCategorys(category)}>查看子分类</Button>
            ) : null
          }
        </Space>
      ),
    },
  ];

  // 获取一级/二级分类列表
  getCategorys = async (receiveParentId = this.state.parentId) => {
    const { dispatch } = this.props;
    const parentId = receiveParentId
    dispatch({
      type: 'categorys/fetchCategorys',
      payload: { parentId },
      callback: (categorys) => {
        // 读取分类列表的数据(可能是一级/二级分类列表)
        if (parentId === '0') {
          // 更新保存一级分类状态
          this.setState({ categorys })
        }else {
          // 更新保存二级分类状态
          this.setState({ subCategorys: categorys })
        }
      }
    })
  };

// 获取指定一级分类的二级列表
  showSubCategorys = (category) => {
    const { _id, name } = category
    this.setState({
      parentId: _id,
      parentName: name
    }, () => {
      this.getCategorys()
    })
  };

  // 获取指定二级分类的一级级列表
  showCategorys = () => {
    this.setState({
      subCategorys: [],
      parentName: '',
      parentId: '0'
    })
  };

// 显示添加分类对话框
  showAddModal = () => {
    const { parentId } = this.state
    this.setState({
      showStaus: 1,
      addAllFields: [
        {
          name: ['parentId'],
          value: parentId
        },
        {
          name: ['categoryName'],
          value: ''
        },
      ]
    })
  }

  // 显示修改分类对话框
  showUpdateModal = (category = {name: '', _id: ''}) => {
    // this.category = category || { name: '', _id: '' }
    const categoryName = category.name
    const categoryId = category._id
    this.setState({
      showStaus: 2,
      allFields: [
        {
          name: ['categoryName'],
          value: categoryName
        },
      ],
      categoryId
    })
  };

  // 隐藏添加/修改对话框
  onCanel = () => {
    this.setState({ showStaus: 0 })
  }

  // 确认添加分类
  addCategory = async () => {
    // 1. 隐藏确认框
    this.setState({ showStaus: 0 })
    const { categoryName, parentId } = this.state.form.getFieldValue()
    // 清除输入数据
    this.state.form.resetFields()
    // 2. 发送添加分类
    try {
      const { msg, status } = await reqAddCategory({
        payload: {
          data: {categoryName, parentId,}
        }
      })
      if (status === 0 ) {
        if (parentId === this.state.parentId) {
          // 添加的分类就是当前列表下的分类
          // 3. 重新获取列表
          this.getCategorys()
        }else if (parentId === '0') {
          // 在二级分类列表下添加一级分类, 重新获取一级分类列表,但不需要显示一级列表
          this.getCategorys('0')
        }
        message.success('添加分类列表成功!')
      }else {
        message.error(msg)
      }
    }catch (e) {
      console.log(e)
    }
  }

  // 确认修改分类
  updateCategory = async () => {
    try {
      // 1. 隐藏对话框
      this.setState({showStaus: 0})
      const { categoryId } = this.state
      const categoryName = this.state.form.getFieldValue('categoryName')
      // 清除输入数据
      this.state.form.resetFields()
      // 2. 发送更新分类
      const { status, msg } = await reqUpdateCategory({
        payload: {
          data:{categoryId, categoryName}
        }
      })
      if (status === 0) {
        // 3. 重新获取列表
        this.getCategorys()
        message.success('更新分类名称成功!')
      }else {
        message.error(msg)
      }
    }catch (e) {
      console.log(e);
    }
  };

  form = (form) => {
    this.setState({form})
  }

  onAddFieldsDataChange = (data) => {
    this.setState({addAllFields: data})
  }

  onFieldsDataChange = (data) => {
    this.setState({allFields: data})
  }

  componentDidMount() {
    // 异步获取一级分类列表
    this.getCategorys()
  }


  render() {
    const { isLoading } = this.props
    const { parentId, categorys, subCategorys, parentName, showStaus, addAllFields, allFields } = this.state
    const title = parentId === '0' ? '一级分类列表' : (
      <div>
        <Button onClick={this.showCategorys} type="link" style={{fontSize: 16}}>一级分类列表</Button>
        <ArrowRightOutlined />
        <span style={{marginLeft: 12}}>{parentName}</span>
      </div>
    )
    return (
      <PageContainer>
        <Card
          title={title}
          extra={<Button onClick={this.showAddModal} type="primary" ><PlusOutlined />添加</Button>}>
          <Table
            columns={this.columns}
            dataSource={parentId === '0' ? categorys : subCategorys}
            bordered
            rowKey="_id"
            loading={isLoading}
            pagination={{
              defaultPageSize: 5,
              pageSizeOptions: ['5', '10', '20', '30'],
              showQuickJumper: true
            }}
          />
          <Modal title="添加分类" visible={showStaus === 1} onOk={this.addCategory} onCancel={this.onCanel} okText="确定 " cancelText="取消">
            <AddForm
              categorys={categorys}
              addAllFields={addAllFields}
              onAddFieldsDataChange={this.onAddFieldsDataChange}
              setForm={this.form}
            />
          </Modal>
          <Modal title="修改分类" visible={showStaus === 2} onOk={this.updateCategory} onCancel={this.onCanel} okText="确定 " cancelText="取消">
            <UpdateForm
              setForm={this.form}
              allFields={allFields}
              onFieldsDataChange={this.onFieldsDataChange}
            />
          </Modal>

        </Card>
      </PageContainer>
    );
  }
}

export default connect(({ categorys, loading }) => ({
  ...categorys,
  isLoading: loading.effects['categorys/fetchCategorys'],
}))(index);
/*
商品分类
 */
